/*
 * @Author: ZL
 * @Date:   2019/05/15
 * @Last Modified by:   ZL
 * @Last Modified time: $ $
 */
var vm = new Vue({
	el: '#portal',
	mixins: [MIXINS.COMM],
	data: function () {
		var _that = this;
		var checkSame = function (rule, value, callback) {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== _that.editPasswordData.newPassword) {
				callback(new Error('两次输入密码不一致！'));
			} else {
				callback();
			}
		};
		var checkDiffer = function (rule, value, callback) {

			//密码包含 数字,英文,字符中的两种以上，长度8-20
			var patrn = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,20}$";
			var re = new RegExp(patrn);
			if (value === '') {
				callback(new Error('请输入密码'));
			} else if (value == _that.editPasswordData.oldPassword) {
				callback(new Error('新密码和原密码不能相同！'));
			} else if (!re.test(value)) {
				callback(new Error('密码需含数字,英文,字符的两种，长度8-20'));
			} else {
				callback();
			}
		};
		var checkOldPass = function (rule, value, callback) {
			if (value === '') {
				callback(new Error('请输入原密码'));
			} else {
				request('opus-admin', {
					url: ctx + 'opus/front/om/users/passwordCheckout',
					data: { oldPassword: value },
					type: 'get'
				}, function (data) {
					if (data.success) {
						callback();
					} else {
						callback(new Error(data.message ? data.message : '原密码错误'));
					}
				})
			}
		};
		return {

			headerData: [], // 头部菜单所有data
			leftData: [],  // 左侧菜单data
			headerActive: 0,  // 头部菜单active状态
			curWidth: (document.documentElement.clientWidth || document.body.clientWidth),//当前屏幕宽度
			curHeight: (document.documentElement.clientHeight || document.body.clientHeight),//当前屏幕高度
			showMenuMore: false,  // 展示更多菜单默认隐藏
			menuCount: 1, // 头部菜单展示条数 menuCount+1
			loginName: '', // 用户登陆名
			userName: '', // 用户名
			userId: '',  // 用户id
			orgList: [], // 用户所属部门可能多个
			fOrgInfo: {}, //
			activeTabIframe: '', // 顶部选项卡 绑定active
			activeTabData: [], // 顶部选项卡 所有展示的tab
			tabIndex: [], // 顶部选项卡 所有展示的tab的key
			hideHeaderData: [], // 头部菜单展示data
			headerDataShow: [], // 头部菜单隐藏data
			showMoreItem: false, // 是否展示隐藏的头部菜单
			leftMenuActive: 0, // 左侧菜单active
			editUserInfoFlag: false, // 是否展示个人信息topbar
			showUserInfo: false, // 是否展示个人信息弹窗
			editPasswordFlag: false, // 是否展示修改密码弹窗
			userInfoFlag: false,
			userCommitsFlag: false,
			editPasswordData: {
				oldPassword: '',
				newPassword: '',
				newPasswordCheck: ''
			}, // 修改密码data
			newPasswordCheck: '', // 再次确认新密码
			editPasswordRule: {
				oldPassword: [
					{ validator: checkOldPass, required: true, trigger: 'blur' },
				],
				newPassword: [
					{ validator: checkDiffer, required: true, trigger: 'blur' }
				],
				newPasswordCheck: [
					{ validator: checkSame, required: true, trigger: 'blur' }
				]
			},  // 修改密码校验
			topOrgId: '',
			userSex: '',
			userEmail: '',
			showTabOpt: false,
			tabOptTop: '',
			tabOptleft: '',
			tabId: '',
			tabKey: '',
			leftClosed: false,
			isFullScreen: true,
			intervalTime: null, // 定时获取消息条数周期
			messgeCount: 0,
			noticeCount: 0,
			ctx: ctx,
			portalTitle: null,
			portalLogoUrl: null,
			activeTabSelData: {}, // addTab新开窗口的数据
			userData: {}, // 用户详细信息
			commentsList: [], // 个人常用意见
			editAddTitle: '', //
			submitCommentsFlag2: false, //
			commentInfo: {},
			editCommitFlag: true, // 编辑意见
			logoutSrc: [], // 退出登录列表
			logoutIframe: false, // 是否退出
			intervalSec: 60, // 默认第一个定时器为60秒
			intervalTimeStep: 1,// 间隔多少秒请求一个菜单红点数据
			registeredCode: [],
			closeInterval: true,
			hasBadgeIsLoading: false,
			needRequestQueue: [],
			forceHint: false, // 是否强制消息提醒
			msgList: [], // 所有未读消息
			notifyedTodo: false, // 是否已提醒过待办
			notifyDomDic: {}, // 通过rangeId找到消息dom实例
			notifyDomIds: [], // 已经展示过的消息id
			TODOMENUTEXT: '待办任务', // 待办任务文本，用来匹配
			todoMenuObj: {}, // 待办任务菜单数据
			todoMenuIndex: 0, // 待办菜单所在数组下标
			todoMsgList: [], // 待办消息
			todoMsgIds: [], // 待办消息rangeId
			todoIndex: 0, // 待办消息当前index
			MAINMENUTEXT: '主办任务', // 主办任务文本，用来匹配
			mainMenuObj: {}, // 主办任务菜单数据
			mainIndex: 0, // 主办菜单所在数组下标
			mainMsgList: [], // 主办消息
			mainMsgIds: [], // 主办消息rangeId
			mainIndex: 0, // 主办消息当前index
			UNMAINMENUTEXT: '协办任务', // 协办任务文本，用来匹配
			unmainMenuObj: {}, // 协办任务菜单数据
			unmainMenuIndex: 0, // 协办菜单所在数组下标
			unmainMsgList: [], // 协办消息
			unmainMsgIds: [], // 协办消息rangeId
			unmainIndex: 0, // 协办消息当前index

			urgeMsgList: [], // 催办消息
			urgeMsgIds: [], // 催办消息rangeId
			urgeIndex: 0, // 催办消息当前index
			msgIntervalTime: 180,
		}
	},
	mounted: function () {
		var _that = this;
		// this.forceHint = (localStorage.getItem('forceHint') == '1');
		window.addEventListener("resize", function () {
			vm.curWidth = document.documentElement.clientWidth;
			vm.curHeight = document.documentElement.clientHeight;
			vm.setHeaderShow();
			if (!_that.checkFull()) {
				_that.isFullScreen = true;
			} else {
				_that.isFullScreen = false;
			}
		});
		//在document挂载onlick事件
		document.addEventListener("click", this.displayMenuPopover)
		// 监听子页面的传递过来的数据
		if (window.addEventListener) {
			window.addEventListener('message', _that.onMessage, false);
		} else {
			if (window.attachEvent) {
				window.attachEvent("onmessage", _that.onMessage);
			}
		}
		_that.getUserIndo();
		// 未读公告
		_that.getCountAoaMsgRangeForMyReceiveUnReaded();
		setInterval(function () {
			_that.getCountAoaMsgRangeForMyReceiveUnReaded();
		}, _that.msgIntervalTime * 1000);
		//获取门户标题及logo url
		_that.initPortal();
		window.setInterval(function () {
			if (_that.needRequestQueue.length != 0) {
				var _target = _that.needRequestQueue.shift();
				_that.getSingleMenuBadge(_target);
			}
		}, _that.intervalTimeStep * 1000);
	},
	watch: {
		forceHint: function (val) {
			localStorage.setItem('forceHint', val ? 1 : 0);
		},
	},
	methods: {
		changeForceHint: function(val){
			var vm = this;
			this.http({
				url: 'opus/front/om/user/info/enableOrDisableRemind.do',
				type: 'post',
				data: { userId: vm.userId },
				success: function(){
					if (val){
						text = '消息强提醒已开启';
					} else {
						text = '已关闭消息强提醒';
					}
					vm.$message.success(text);
				},
				error: function(res){
					vm.forceHint = !vm.forceHint;
					vm.$message.error(res.message || '操作失败');
				},
				fail: function(){
					vm.forceHint = !vm.forceHint;
					vm.$message.error('请求服务器失败');
				},
			});
		},
		// 点击单条待办、主办、协办
		clickTabRow: function(row, type){
			var vm = this;
			this.readMsg(row.rangeId, function(){
				vm.openTabMenu(row, type);
				vm.getUnReadMsgCount();
				if (type == 'todo') {
					if (vm.todoIndex > 0) {
						vm.todoIndex --;
					}
				}
				if (type == 'main') {
					if (vm.mainIndex > 0) {
						vm.mainIndex --;
					}
				}
				if (type == 'unmain') {
					if (vm.unmainIndex > 0) {
						vm.unmainIndex --;
					}
				}
			});
		},
		// 点击单条催办
		clickUrgeRow: function(row){
			var vm = this;
			if (row.jumpMode == 'iframe') {
				window.open(ctx + row.jumpUrl);
			} else {
				vm.openMsgTab();
			}
			this.readMsg(row.rangeId, function(){
				vm.getUnReadMsgCount();
				if (vm.urgeIndex > 0) {
					vm.urgeIndex --;
				}
			});
		},
		// 某个list，所有消息全部标记为已读
		allReadMsg: function(listStr){
			var vm = this;
			var list = this[listStr] || [];
			var len = list.length;
			this.loadingCount++;
			list.forEach(function(u){
				vm.readMsg(u.rangeId, function(){
					if (--len == 0) {
						vm.loadingCount--;
						vm[listStr] = [];
						vm.getUnReadMsgCount();
					}
				});
			});
		},
		// 标记某条rangeId为已读
		readMsg: function(id, cb){
			request('agx', {
				url: ctx + 'rest/aoa/msg/range/updateAoaMsgRangeReaded',
				type: 'post',
				data: { rangeId: id },
			}, function () {
				typeof cb === 'function' && cb();
			}, function () {
				typeof cb === 'function' && cb();
			})
		},
		// 点击消息翻页
		clickMsgPage: function(type, step){
			var listStr = '';
			var indexStr = ''; 
			if (type == 'todo'){
				listStr = 'todoMsgList';
				indexStr = 'todoIndex';
			} else if (type == 'main'){
				listStr = 'mainMsgList';
				indexStr = 'mainIndex';
			} else if (type == 'unmain'){
				listStr = 'unmainMsgList';
				indexStr = 'unmainIndex';
			} else if (type == 'urge'){
				listStr = 'urgeMsgList';
				indexStr = 'urgeIndex';
			}
			var len = this[listStr].length;
			var oldIndex = this[indexStr];
			var nowIndex = oldIndex + step;
			if (nowIndex < 0) {
				nowIndex = len -1;
			} else if (nowIndex > (len - 1)) {
				nowIndex = 0;
			}
			this[indexStr] = nowIndex;
		},
		// find menu obj
		// key 字段名  val 字段值
		findMenuObj: function (key, val) {
			var o = {};
			var index = 0;
			var flag = false;
			this.headerData.forEach(function (u, i) {
				if (flag) return null;
				var cList = u.childrenList || [];
				cList.forEach(function (uu, ii) {
					if (flag) return null;
					var ccList = uu.childrenList || [];
					if (ccList.length) {
						ccList.forEach(function(uuu, iii){
							if (uuu[key] === val){
								flag = true;
								o = uuu;
								index = iii;
							}
						})
					} else if (uu[key] == val) {
						flag = true;
						o = uu;
						index = ii;
					}
				});
			});
			return { o: o, index: index }
		},
		// 找到待办任务菜单数据
		findTodoMenu: function () {
			var obj = this.findMenuObj('menuName', this.TODOMENUTEXT);
			this.todoMenuObj = obj.o;
			this.todoMenuIndex = obj.index;
		},
		// 打开待办、主办、协办任务菜单
		openTabMenu: function (row, type) {
			var str = '';
			if (type == 'todo') {
				str = this.TODOMENUTEXT;
			}
			if (type == 'main') {
				str = this.MAINMENUTEXT;
			}
			if (type == 'unmain') {
				str = this.UNMAINMENUTEXT;
			}
			var obj = this.findMenuObj('menuName', str);
			this.addTab(null, obj.o, null, obj.index, obj.o.pageOpenMode);
			// this.addTab(null, this.todoMenuObj, null, this.todoMenuIndex, this.todoMenuObj.pageOpenMode);
		},
		// 判定是否为待办消息
		judgeIsTodoMsg: function(o){
			return o.contentSimpleTitle == this.TODOMENUTEXT;
		},
		// 判定是否为主办消息
		judgeIsMainMsg: function(o){
			return o.contentSimpleTitle == this.MAINMENUTEXT;
		},
		// 判定是否为协办消息
		judgeIsUnmainMsg: function(o){
			return o.contentSimpleTitle == this.UNMAINMENUTEXT;
		},
		// 判定是否为催办消息
		judgeIsUrgeMsg: function(o){
			return o.jumpMode == 'iframe';
		},
		//获取门户标题及logo url
		initPortal: function () {
			var _that = this;
			request('opus-front', {
				url: ctx + 'opus/front/config',
				type: 'get',
			}, function (data) {
				if (data.success) {
					_that.portalTitle = data.content.title;
					if (_that.portalTitle != null)
						$("title").html(_that.portalTitle);
					_that.portalLogoUrl = data.content.logoUrl;
				}
			}, function (msg) {
				alertMsg('', '服务请求失败', '关闭', 'error', true);
			});
		},
		getUserIndo: function () { // 获取用户登陆信息
			var _that = this;
			request('opus-admin', {
				url: ctx + 'opus/front/om/users/currOpusLoginUser',
				// url: '../../../../../static/agcloud/framework/ui-schemes/third-level-protal/js/user_1.json',
				type: 'get',
			}, function (data) {
				if (data.success) {
					// data.content.orgs = [{
					//   isMain: null,
					//   orgCode: 'R029-G685',
					//   orgId: '',
					//   orgName: '佛山市三水区住房城乡建设和水利局',
					//   orgSeq: '',
					// }, {
					//   isMain: null,
					//   orgCode: 'R029-G685',
					//   orgId: '',
					//   orgName: '佛山市自然资源局',
					//   orgSeq: '',
					// }];
					_that.orgList = data.content.orgs || [];
					var orgList = _that.orgList;
					if (orgList && orgList.length) {
						_that.fOrgInfo.shortName = orgList[0].orgSeq;
						_that.fOrgInfo.orgName = orgList[0].orgName;
					}
					_that.loginName = data.content.user.loginName;
					_that.userName = data.content.user.userName;
					_that.userId = data.content.user.userId;
					_that.topOrgId = data.content.currentOrgId
					_that.getHeaderData();
					_that.getUserAllInfo(data.content.user.loginName);
					_that.getLogoutUrls();
				}
			}, function (msg) {
				alertMsg('', '服务请求失败', '关闭', 'error', true);
			});
		},
		getUserAllInfo: function (loginName) { // 获取登录用户所有信息
			var _that = this;
			request('agx', {
				// url: '../../../../../static/agcloud/framework/ui-schemes/third-level-protal/js/user_2.json',
				url: ctx + 'opus/front/om/users',
				type: 'get',
				data: { loginName: loginName }
			}, function (data) {
				if (data.success) {
					_that.userEmail = data.content.userEmail;
					_that.userSex = data.content.userSex;
					_that.userData = data.content;
					if (_that.userData.userAssignDate) {
						var userAssignDate = formatDate(new Date(_that.userData.userAssignDate), 'yyyy-MM-dd');
						_that.userData.userAssignDate = userAssignDate;
					}
					_that.forceHint = (data.content.enableStrongRemind == 1);
					// 未读消息
					_that.getUnReadMsgCount();
					setInterval(function () {
						_that.getUnReadMsgCount();
					}, _that.msgIntervalTime * 1000);
				}
			}, function (msg) {
				alertMsg('', '服务请求失败', '关闭', 'error', true);
			});
		},
		// 给menuInnerUrl加上menuCode数据，方便刷新badge红点数据
		handleInnerUrl: function (arr) {
			var _this = this;
			arr.forEach(function (u) {
				if (u.openMenuCount && u.menuCountUrl) {
					var chart = '?';
					if (u.menuInnerUrl.split('?').length > 1) {
						chart = '&';
					}
					u.menuInnerUrl += (chart + 'refreshBadgeCode=' + u.menuCode);
				}
				if (u.childrenList && u.childrenList.length) {
					_this.handleInnerUrl(u.childrenList);
				}
			});
		},
		// 通过menucode来刷新对应的badge，不传为刷新所有
		refreshBadgeCount: function (code) {
			this.getViewDataCountByViewCode(this.leftData, code);
		},
		getHeaderData: function () { // 获取菜单数据
			var _that = this;
			var props = {
				isTree: 'true',
				netName: '前端网络入口',
				tmnId: '1',
				topOrgId: _that.topOrgId,
				userId: _that.userId
			};
			var _that = this;
			request('opus-admin', {
				url: ctx + 'opus/front/om/users/user/' + _that.userId + '/allMenus',
				// url: '../../../../../static/agcloud/framework/ui-schemes/third-level-protal/js/menu_2.json',
				type: 'get',
				data: props
			}, function (data) {
				_that.handleInnerUrl(data.content);
				_that.headerData = data.content;
				_that.findTodoMenu();
				_that.setHeaderShow();
				if (data.content && data.content.length > 0) {
					if (data.content[0].childrenList) {
						_that.leftData = data.content[0].childrenList;
						_that.activeTabData.push({
							menuName: _that.leftData[0].menuName,
							id: _that.leftData[0].id,
							menuInnerUrl: _that.leftData[0].menuInnerUrl
						});
						_that.tabIndex.push(_that.leftData[0].id);
					} else {
						_that.activeTabData.push({
							menuName: data.content[0].menuName,
							id: data.content[0].id,
							menuInnerUrl: data.content[0].menuInnerUrl
						});
						_that.tabIndex.push(data.content[0].id);
					}
					_that.activeTabIframe = _that.activeTabData[0].id;
					_that.$nextTick(function () {
						_that.menuAddActive();
					});
					_that.getViewDataCountByViewCode(_that.leftData);
				}
			}, function (msg) {
				alertMsg('', '服务请求失败', '关闭', 'error', true);
			});
		},
		setHeaderShow: function () {  // 设置头部可展示菜单长度
			var _that = this;
			var logoWidth = $('.protal-header .subsystem-name').outerWidth(true);
			var topbarWidth = $('.user-info-topbar').outerWidth(true);
			var width = _that.curWidth - logoWidth - topbarWidth;
			if (_that.headerData !== null && _that.headerData.length > 0) {
				var count = parseInt(width / 140);
				if (count < _that.headerData.length && count > 0) {
					_that.showMenuMore = true;
					_that.menuCount = count - 1;
				} else if (count < 0 || count == 0) {
					_that.showMenuMore = true;
					_that.menuCount = 0;
				} else {
					_that.showMenuMore = false;
					_that.menuCount = _that.headerData.length;
				}
			} else {
				_that.showMenuMore = false;
				_that.menuCount = _that.headerData.length;
			}
			_that.initMenuCount(_that.headerData, _that.menuCount)
		},
		initMenuCount: function (eleLi, n) {  // 重置头部菜单
			if (eleLi) {
				this.headerDataShow = eleLi.slice(0, n);
				this.hideHeaderData = eleLi.slice(n)
			}
		},
		headerChangeMenu: function (data, index, e) { // 头部菜单点击事件
			var _that = this;
			if (!data.childrenList) {
				_that.addTab(e, data, this.activeTabIframe, index, data.pageOpenMode)
			} else {
				_that.headerActive = index;
				_that.leftData = data.childrenList;
				_that.showMoreItem = false;
				_that.leftMenuActive = -1;
				_that.getViewDataCountByViewCode(_that.leftData);
				_that.$nextTick(function () {
					_that.menuAddActive();
				})
				$(e.srcElement).addClass('m-menu__item--active').siblings('.m-menu__item--active').removeClass('m-menu__item--active');
				$(e.srcElement).parents('.m-menu__item').addClass('m-menu__item--active').siblings('.m-menu__item--active').removeClass('m-menu__item--active');

			}
		},
		addTab: function (ev, data, activeTab, ind, openFlag) { // 点击新增顶部tab openFlag打开方式
			if (ev) {
				ev.cancelBubble = true;
			}
			this.leftMenuActive = ind;
			this.activeTabSelData = data;
			if (openFlag == 'win') {
				window.open(data.menuInnerUrl);
				return false;
			};
			if (!data.childrenList && (this.tabIndex.indexOf(data.id) == -1)) {
				this.activeTabData.push({
					menuName: data.menuName,
					id: data.id,
					menuInnerUrl: data.menuInnerUrl
				});
				this.activeTabIframe = data.id;
				this.menuAddActive();
				this.tabIndex.push(data.id);
			} else {
				this.activeTabIframe = data.id;
				this.menuAddActive();
			}
		},
		removeTab: function (targetName) { // 移除顶部tab
			var tabs = this.activeTabData;
			var activeName = this.activeTabIframe;
			var _that = this;
			this.showTabOpt = false;
			if (activeName === targetName) {
				tabs.forEach(function (tab, index) {
					if (tab.id === targetName) {
						var nextTab = tabs[index + 1] || tabs[index - 1];
						if (nextTab) {
							activeName = nextTab.id;
						}
					}
				});
			}
			_that.activeTabIframe = activeName;
			_that.menuAddActive();
			_that.activeTabData = tabs.filter(function (tab) { return tab.id !== targetName });
			_that.tabIndex = [];
			_that.activeTabData.forEach(function (e) {
				_that.tabIndex.push(e.id);
			});
		},
		closeActiveTab: function () {
			try {
				$('#tab-' + vm.activeTabIframe + ' .el-icon-close').trigger('click');
			} catch (e) { console.error(e) }
		},
		tabMouseRightClick: function (ev) { // 顶部tab 右击事件
			ev.cancelBubble = true;
			if (ev.path) {
				this.tabId = ev.path[0].id;
				this.tabKey = ev.path[0].id.split('tab-')[1];
			} else {
				this.tabId = ev.srcElement.id
				this.tabKey = ev.srcElement.id.split('tab-')[1];
			}
			if (!(this.tabId.indexOf('tab-MENU_') > -1)) {
				return false;
			} else {
				this.showTabOpt = true;
				this.tabOptTop = ev.offsetY;
				if ($('body').hasClass('demo2')) {
					this.tabOptleft = ev.clientX - 90;
				} else {
					this.tabOptleft = ev.clientX - 170;
				}
				this.activeTabIframe = this.tabKey;
				this.menuAddActive();
			}
		},
		closeOther: function () { // 移除其他顶部tab
			var start = this.tabIndex.indexOf(this.tabKey);
			this.tabIndex = this.tabIndex.slice(start, start + 1);
			this.activeTabData = this.activeTabData.slice(start, start + 1);
			this.showTabOpt = false;
		},
		closeLeft: function () { // 移除左边顶部tab
			var start = this.tabIndex.indexOf(this.tabKey);
			this.tabIndex = this.tabIndex.slice(start);
			this.activeTabData = this.activeTabData.slice(start);
			this.showTabOpt = false;
		},
		closeRight: function () { // 移除右边顶部tab
			var start = this.tabIndex.indexOf(this.tabKey);
			this.tabIndex = this.tabIndex.slice(0, start + 1);
			this.activeTabData = this.activeTabData.slice(0, start + 1);
			this.showTabOpt = false;
		},
		changeTab: function () {  // tab点击事件
			var tabEle = $('.el-tabs__content .el-tab-pane');
			var tabEleLen = tabEle.length;
			var _that = this;
			_that.menuAddActive();
		},
		changeLeftClosed: function (flag) { // 左边栏展开收缩事件
			if (flag) {
				this.leftClosed = false
			} else {
				this.leftClosed = true
			}
		},
		displayMenuPopover: function () { // 隐藏tab操作窗口
			this.showTabOpt = false;
		},
		onMessage: function (e) {
			var _that = this
			var data = e.data
			if (!data.vueDetected && data.id != undefined) {
				data.menuInnerUrl = e.origin + data.menuInnerUrl
				_that.addTab(e, data, 'MENU_' + data.id, _that.leftMenuActive++);
			}
		},
		// 获取登出地址
		getLogoutUrls: function () {
			var _that = this;
			request('opus-admin', {
				url: ctx + 'opus/front/om/users/listLogoutUrl',
				type: 'get',
				data: {
					netName: '前端网络入口',
					orgId: _that.topOrgId,
					userId: _that.userId
				}
			}, function (result) {
				if (result.success) {
					_that.logoutSrc = result.content;
				} else {
					_that.logoutSrc = [];
				}
			}, function (msg) {
				// 获取登出地址失败

			});
		},
		logout: function (e) { // 退出登陆
			e.cancelBubble = true;
			var _that = this;
			confirmMsg('', '确定要退出登陆吗？', function () {
				_that.logoutIframe = true;
				_that.$nextTick(function () {
					setTimeout(function () {
						window.location.href = ctx + 'logout';
					}, 500);
				});
			}, function () {
				_that.logoutIframe = false;
			})
		},
		editPasswordSubmit: function () { // 修改密码
			var _that = this;
			_that.$refs['editPasswordData'].validate(function (valid) {
				if (valid) {
					var props = {
						newPassword: _that.editPasswordData.newPassword,
						oldPassword: _that.editPasswordData.oldPassword,
					};
					request('opus-admin', {
						url: ctx + 'opus/front/om/users/password',
						data: props,
						type: 'post'
					}, function (data) {
						if (data.success) {
							_that.$message({
								message: '密码修改成功',
								type: 'success'
							});
							_that.editPasswordFlag = false;
						} else {
							_that.$message({
								message: data.message ? data.message : '密码修改失败',
								type: 'error'
							});
						}
					}, function (msg) {
						_that.$message({
							message: msg.message ? msg.message : '密码修改失败',
							type: 'error'
						});
					})
				} else {
					alertMsg('', '请输入完整且正确的信息', '关闭', 'warning', true);
					return false;
				}
			});
		},
		clearDialogData: function (formName) { // 清空表单
			this.$refs[formName].resetFields();
		},
		toggleFullScreen: function () { // 切换全屏
			if (this.isFullScreen) {
				this.enterfullscreen()
			} else {
				this.exitfullscreen();
			}
		},
		enterfullscreen: function () {//进入全屏
			var docElm = document.documentElement;
			//W3C
			if (docElm.requestFullscreen) {
				docElm.requestFullscreen();
			}
			//FireFox
			else if (docElm.mozRequestFullScreen) {
				docElm.mozRequestFullScreen();
			}
			//Chrome等
			else if (docElm.webkitRequestFullScreen) {
				docElm.webkitRequestFullScreen();
			}
			//IE11
			else if (docElm.msRequestFullscreen) {
				docElm.msRequestFullscreen();
				var widthFull = $(window).width();
				$('#wrapper').css('width', widthFull);
			} else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
				var wscript = new ActiveXObject("WScript.Shell");
				if (wscript !== null) {
					wscript.SendKeys("{F11}");
				}
			}
			this.isFullScreen = true;
		},
		exitfullscreen: function () { //退出全屏
			if (document.exitFullscreen) {
				document.exitFullscreen();
			}
			else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			}
			else if (document.webkitCancelFullScreen) {
				document.webkitCancelFullScreen();
			}
			else if (document.msExitFullscreen) {
				document.msExitFullscreen();
			} else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
				var wscript = new ActiveXObject("WScript.Shell");
				if (wscript !== null) {
					wscript.SendKeys("{F11}");
				}
			}
			this.isFullScreen = false;
		},
		checkFull: function () { // 判断是否全屏
			var isFull = document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
			if (isFull === undefined) { isFull = false; }
			return isFull
		},
		showEditUserInfo: function () { // 是否展示login-info
			this.editUserInfoFlag = !this.editUserInfoFlag;
		},
		menuAddActive: function () {
			$('.protal-content-left .el-menu-item').removeClass('is-active');
			$('#' + this.activeTabIframe).addClass('is-active').siblings('.el-menu-item').removeClass('is-active');
		},
		setBadgeInterval: function (code) {
			var vm = this;
			if (vm.closeInterval) return null;
			if (vm.registeredCode.indexOf(code) == -1) {
				window.setInterval(function () {
					vm.refreshBadgeCount(code);
				}, vm.intervalSec * 1000);
				vm.registeredCode.push(code);
				vm.intervalSec += vm.intervalTimeStep;
			}
		},
		getSingleMenuBadge: function (e) {
			var _that = this;
			_that.$set(e, 'isLoading', true);
			request('opus-admin', {
				url: ctx + e.menuCountUrl,
				type: 'get',
			}, function (data) {
				_that.$set(e, 'isLoading', false);
				if (data) {
					var count = 0;
					if (typeof (data.success) !== "undefined") {
						if (data.success) {
							count = data.content.total;
						}
					} else if (data.total) {
						count = data.total;
					} else {
						count = data;
					}
					e.subCount = count;
				}
			}, function (msg) {
				_that.$set(e, 'isLoading', false);
				_that.$message({
					message: '服务请求失败',
					type: 'error'
				});
			});
		},
		// 得到菜单badge数据，传menuCode为刷新单个，不传为刷新所有
		getViewDataCountByViewCode: function (arr, menuCode) {
			var totalCount = 0;
			var _that = this;
			var leftData = arr || this.leftData;
			if (leftData.length == 0) { return false }
			leftData.map(function (unit) {
				var e = unit;
				if (e.openMenuCount) {
					if (menuCode && menuCode.length && e.menuCode != menuCode) {
						// 传入menuCode即为刷新指定code菜单，不相同的都不用刷新
						return null;
					}
					if (_that.registeredCode.indexOf(e.menuCode) != -1 && !menuCode) {
						// 假如已经在轮询中了，并且没有传入menuCode就不需要在请求刷新了
						return null;
					}
					_that.intervalTime = e.menuCountInterval;
					_that.setBadgeInterval(e.menuCode);
					_that.needRequestQueue.push(e);
				} else if (e.childrenList) {
					_that.getViewDataCountByViewCode(e.childrenList);
				}
			});
		},
		emptyFunc: function () { },
		clickUnitMsg: function (ev, row) {
			console.log(row.rangeId);
			// if (isDevelop) return null;
			var vm = this;
			var rangeId = row.rangeId;
			// 标记位已读
			request('agx', {
				url: ctx + 'rest/aoa/msg/range/updateAoaMsgRangeReaded',
				type: 'post',
				data: { rangeId: rangeId },
			}, function () {
				vm.notifyDomDic[rangeId] && vm.notifyDomDic[rangeId].close();
				vm.notifyDomDic[rangeId] = null;
				if (row.jumpMode == 'iframe') {
					// 打开浏览器新页面
					window.open(ctx + row.jumpUrl);
				} else if (row.jumpMode == 'tab') {
					// 新增tab
					var title = row.contentTitle;
					var targetLen = 8;
					var titleLen = title.length;
					var needSlice = (titleLen > targetLen);
					var menuName = title.slice(0, needSlice ? targetLen : titleLen) + (needSlice ? '...' : '');
					menuName = row.contentSimpleTitle || menuName || '消息提醒';
					vm.addTab(ev, {
						menuName: menuName, id: Date.now() + '_msg', menuInnerUrl: ctx + row.jumpUrl
					}, vm.activeTabIframe, '');
				} else {
					//  打开消息tab
					vm.openMsgTab(ev);
				}
				try {
					vm.getMsgList();
				} catch (e) { }
			}, function () {
				vm.$message.error('请求服务器接口出错了');
			})
		},
		cNotify: function (id) {
			var vm = this;
			return function () {
				vm.clickNotify(id);
			}
		},
		clickNotify: function (id) {
			var index = -1;
			this.msgList.forEach(function (u, i) {
				if (u.rangeId == id) {
					index = i;
				}
			})
			if (index != -1) {
				this.clickUnitMsg(null, this.msgList[index]);
			}
		},
		closeGlobalNotify: function (nvm) {
			var vm = this;
			var rangeId = nvm.customClass.split(' ')[1];
			vm.notifyDomDic[rangeId] = null;
			console.log(rangeId);
			// if (isDevelop) return null;
			// 标记为已读
			request('agx', {
				url: ctx + 'rest/aoa/msg/range/updateAoaMsgRangeReaded',
				type: 'post',
				data: { rangeId: rangeId },
			}, function () {
				vm.getMsgList();
			}, function () {
				vm.$message.error('请求服务器接口出错了');
			})
		},
		createNotify: function (row) {
			var vm = this;
			vm.notifyDomDic[row.rangeId] = vm.$notify({
				position: 'bottom-right',
				duration: 0,
				type: 'warning',
				customClass: 'global-notify ' + row.rangeId,
				onClick: vm.cNotify(row.rangeId),
				onClose: vm.closeGlobalNotify,
				title: row.contentTitle,
				message: row.contentText,
			});
		},
		openMsgTab: function (event) {
			var vm = this;
			vm.addTab(event, {
				menuName: '我的消息', id: 'myMessge', menuInnerUrl: ctx + '/aoa/msg/index'
			}, vm.activeTabIframe, '');
		},
		clickMsgIcon: function (ev) {
			if (!this.msgList.length) {
				this.openMsgTab(ev);
			}
		},
		judgeNeedNotify: function () {
			var vm = this;
			var text = this.TODOMENUTEXT;
			var index = -1;
			if (vm.msgList.length && vm.forceHint) {
				vm.msgList.forEach(function (u, i) {
					if (index != -1) {
						// 已经找到了，不再匹配
						return null;
					}
					if (vm.notifyDomIds.indexOf(u.rangeId) != -1) {
						// 已经渲染了，不再匹配
						return null;
					}
					if (!vm.notifyedTodo) {
						// 未弹出过待办
						index = i;
					} else {
						// 弹出过待办，渲染下一个非待办的
						if (u.contentSimpleTitle != text) {
							index = i;
						}
					}
				});
				if (index == -1) {
					// 为筛选出需要渲染的，不做渲染
					return null;
				}
				var cRow = vm.msgList[index];
				vm.notifyDomIds.push(cRow.rangeId);
				if (cRow.contentSimpleTitle == text) {
					vm.notifyedTodo = true;
				}
				vm.createNotify(cRow);
			}
		},
		// 获取所有消息数据，过滤未读信息并且分类
		getMsgList: function () {
			var vm = this;
			request('', {
				url: ctx + 'rest/aoa/msg/range/getPageAoaMsgRangeForMyReceive',
				type: 'post',
			}, function (res) {
				if (res.content && res.content.rows) {
					var _list = [];
					res.content.rows.forEach(function (u) {
						if (u.isRead != '1') {
							_list.push(u);
						}
					});
					vm.messgeCount = _list.length;
					vm.msgList = _list;
					var todoList = [];
					var mainMsgList = [];
					var unmainMsgList = [];
					var urgeList = [];
					_list.forEach(function(u){
						if (vm.judgeIsTodoMsg(u)){
							// 待办数据
							if (vm.todoMsgIds.indexOf(u.rangeId)==-1){
								todoList.push(u);
								vm.todoMsgIds.push(u.rangeId);
							}
						} else if (vm.judgeIsMainMsg(u)){
							// 主办消息
							if (vm.mainMsgIds.indexOf(u.rangeId)==-1){
								mainMsgList.push(u);
								vm.mainMsgIds.push(u.rangeId);
							}
						} else if (vm.judgeIsUnmainMsg(u)){
							// 协办消息
							if (vm.unmainMsgIds.indexOf(u.rangeId)==-1){
								unmainMsgList.push(u);
								vm.unmainMsgIds.push(u.rangeId);
							}
						} else if (vm.judgeIsUrgeMsg(u)) {
							// 催办数据
							if (vm.urgeMsgIds.indexOf(u.rangeId)==-1){
								urgeList.push(u);
								vm.urgeMsgIds.push(u.rangeId);
							}
						}
					});
					var todoRangeId = vm.todoMsgList.length ? vm.todoMsgList[vm.todoIndex].rangeId : '';
					var mainRangeId = vm.mainMsgList.length ? vm.mainMsgList[vm.mainIndex].rangeId : '';
					var unmainRangeId = vm.unmainMsgList.length ? vm.unmainMsgList[vm.unmainIndex].rangeId : '';
					var urgeRangeId = vm.urgeMsgList.length ? vm.urgeMsgList[vm.urgeIndex].rangeId : '';
					vm.todoMsgList = todoList.concat(vm.todoMsgList);
					vm.mainMsgList = mainMsgList.concat(vm.mainMsgList);
					vm.unmainMsgList = unmainMsgList.concat(vm.unmainMsgList);
					vm.urgeMsgList = urgeList.concat(vm.urgeMsgList);
					var nowTodoRangeId = -1;
					var nowMainRangeId = -1;
					var nowUnmainRangeId = -1;
					var nowUrgeRangeId = -1;
					vm.todoMsgList.forEach(function(u, index){
						if (u.rangeId == todoRangeId) {
							nowTodoRangeId = index;
						}
					});
					vm.mainMsgList.forEach(function(u, index){
						if (u.rangeId == mainRangeId) {
							nowMainRangeId = index;
						}
					});
					vm.unmainMsgList.forEach(function(u, index){
						if (u.rangeId == unmainRangeId) {
							nowUnmainRangeId = index;
						}
					});
					vm.urgeMsgList.forEach(function(u, index){
						if (u.rangeId == urgeRangeId) {
							nowUrgeRangeId = index;
						}
					});
					if (nowTodoRangeId == -1) {
						nowTodoRangeId = 0;
					}
					if (nowMainRangeId == -1) {
						nowMainRangeId = 0;
					}
					if (nowUnmainRangeId == -1) {
						nowUnmainRangeId = 0;
					}
					if (nowUrgeRangeId == -1) {
						nowUrgeRangeId = 0;
					}
					vm.todoIndex = nowTodoRangeId;
					vm.mainIndex = nowMainRangeId;
					vm.unmainIndex = nowUnmainRangeId;
					vm.urgeIndex = nowUrgeRangeId;
					// vm.judgeNeedNotify();
				}
			});
		},
		// 获取未读消息个数
		getUnReadMsgCount: function () {
			var _that = this;
			request('', {
				url: ctx + 'rest/aoa/msg/range/getCountAoaMsgRangeForMyReceiveUnReaded',
				type: 'post',
			}, function (data) {
				_that.messgeCount = data.content;
				if (_that.forceHint && _that.messgeCount > 0) {
					_that.getMsgList();
				}
				if (_that.messgeCount == 0){
					_that.todoIndex = 0;
					_that.urgeIndex = 0;
					_that.todoMsgList = [];
					_that.urgeMsgList = [];
				}
			});
		},
		// 获取未读公告
		getCountAoaMsgRangeForMyReceiveUnReaded: function () {
			var _that = this;
			request('opus-admin', {
				url: ctx + 'rest/aoa/notice/content/getCountAoaNoticeContent',
				type: 'post',
				data: { businessFlag: 'busiTypeDefault' }
			}, function (data) {
				_that.noticeCount = data.content;
			});
		},
		// 编辑保存用户信息
		editUserInfoSubmit: function () {
			var _that = this;
			var param = {
				userName: _that.userData.userName,
				userCode: _that.userData.userCode,
				userId: _that.userData.userId,
				userFamilyAddress: _that.userData.userFamilyAddress,
				userDomicilePlace: _that.userData.userDomicilePlace,
				userMobile: _that.userData.userMobile,
				userEmail: _that.userData.userEmail,
				userPost: _that.userData.userPost,
				userAssignDate: _that.userData.userAssignDate,
				isRejectSms: _that.userData.isRejectSms
			}
			request('', {
				// url: 'http://192.168.30.37:8080/opus-front/'+'opus/front/om/user/info/saveUserInfo.do',
				url: ctx + 'opus/front/om/user/info/saveUserInfo.do',
				data: param,
				type: 'get'
			}, function (data) {
				if (data.success) {
					_that.$message({
						message: '保存成功',
						type: 'success'
					});
					_that.userInfoFlag = false;
				} else {
					_that.$message({
						message: data.message ? data.message : '保存失败',
						type: 'error'
					});
				}
			}, function (msg) {
				_that.$message({
					message: msg.message ? msg.message : '保存失败',
					type: 'error'
				});
			})
		},
		// 获取个人常用意见
		getCommitsList: function () {
			var _that = this;
			_that.userCommitsFlag = true
			request('', {
				// url: 'http://106.52.77.101:8083/aplanmis-front/rest/comment/getAllActiveUserOpinions',
				url: ctx + 'rest/comment/getAllActiveUserOpinions',
				type: 'get'
			}, function (data) {
				if (data.success) {
					_that.commentsList = data.content;
				} else {
					_that.$message({
						message: data.message ? data.message : '获取个人意见失败',
						type: 'error'
					});
				}
			}, function (msg) {
				_that.$message({
					message: msg.message ? msg.message : '获取个人意见失败',
					type: 'error'
				});
			})
		},
		// 编辑 常用意见
		editCommit: function (rowData) {
			this.submitCommentsFlag2 = true;
			this.editAddTitle = '编辑常用意见'
			this.commentInfo = rowData;
			this.editCommitFlag = true;
		},
		// 删除 常用意见
		deleteUseComment: function (opinionId) {
			var _that = this;
			confirmMsg('确定要删除该意见吗？：', '', function () {
				request('', {
					// url: 'http://106.52.77.101:8083/aplanmis-front/rest/comment/deleteUserOpinion/'+opinionId,
					url: ctx + 'rest/comment/deleteUserOpinion/' + opinionId,
					type: 'DELETE'
				}, function (data) {
					if (data.success) {
						_that.$message({
							message: data.message ? data.message : '删除成功',
							type: 'success'
						});
						_that.getCommitsList();
					} else {
						_that.$message({
							message: data.message ? data.message : '删除失败',
							type: 'error'
						});
					}
				}, function (msg) {
					_that.$message({
						message: msg.message ? msg.message : '删除失败',
						type: 'error'
					});
				})
			}, function () { }, '确定', '取消', 'warning', true)

		},
		// 新增 常用意见
		addCommit: function () {
			this.submitCommentsFlag2 = true;
			this.editAddTitle = '新增常用意见';
			this.commentInfo = {
				comment: '',
			};
			this.editCommitFlag = false;
		},
		// 保存 常用意见
		updateComment: function () {
			var url = '', type = '', param = {};
			var _that = this;
			if (_that.editCommitFlag) {
				// url = 'http://106.52.77.101:8083/aplanmis-front/rest/comment/editUserOpinion'
				url = ctx + 'rest/comment/editUserOpinion'
				type = 'put';
				param = {
					opinionContent: _that.commentInfo.opinionContent,
					opinionId: _that.commentInfo.opinionId,
					sortNo: _that.commentInfo.sortNo
				}
			} else {
				// url = 'http://106.52.77.101:8083/aplanmis-front/rest/comment/saveUserOpinion';
				url = ctx + 'rest/comment/saveUserOpinion'
				type = 'POST';
				param = {
					message: _that.commentInfo.opinionContent,
					sortNo: _that.commentInfo.sortNo
				}
			}
			request('', {
				url: url,
				type: type,
				data: param
			}, function (data) {
				if (data.success) {
					_that.$message({
						message: data.message ? data.message : '保存成功',
						type: 'success'
					});
					_that.submitCommentsFlag2 = false;
					_that.getCommitsList();
				} else {
					_that.$message({
						message: data.message ? data.message : '保存失败',
						type: 'error'
					});
				}
			}, function (msg) {
				_that.$message({
					message: msg.message ? msg.message : '保存失败',
					type: 'error'
				});
			})
		},
	}
});